package com.qnkf.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.qnkf.aop.ApiController;
import com.qnkf.entity.TokenEntity;
import com.qnkf.entity.TokenRequest;
import com.qnkf.enums.ResultEnum;
import com.qnkf.exception.*;
import com.qnkf.model.ResultModel;
import com.qnkf.util.IpUtil;
import com.qnkf.util.JwtUtil;
import com.qnkf.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    protected static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        log.info("前置拦截器1 preHandle： 请求的uri为：" + requestURL.toString());
        try {
            String ip = IpUtil.getIpAddr(httpServletRequest);
            String token = httpServletRequest.getHeader("token");
            log.info("token:{}", token);
            StringBuffer stringBuffer = new StringBuffer(ip).append(requestURL).append(JSON.toJSONString(httpServletRequest.getParameterMap()));
            if (redisUtil.requestLock(stringBuffer.toString())) {
                throw new FrequentlyException();
            }
            TokenRequest request = new TokenRequest();
            request.setIp(ip);
            request.setToken(token);
            if (o instanceof HandlerMethod) {
                HandlerMethod h = (HandlerMethod) o;
                ApiController apiController = h.getMethodAnnotation(ApiController.class);
                if (apiController != null) {
                    //验证是否需要进行登陆校验
                    if (apiController.isLogin()) {
                        if (StringUtils.isEmpty(token)) {
                            //未获取到token抛出异常
                            throw new LoginException("token请求头未设置");
                        }
                        JSONObject userData = JwtUtil.verifyToken(token);
                        if (userData == null) {
                            throw new LoginException("登录失败，token失效");
                        }else {
                            log.info("  userData :{}",JSON.toJSONString(userData));
                        }
                        if (apiController.isParam()) {
                            Object object = httpServletRequest.getAttribute("request");
                            String attribute = null;
                            JSONObject data;
                            if (null != object) {
                                attribute = JSON.toJSONString(object);
                            }
                            if (StringUtils.isEmpty(attribute)) {
                                data = new JSONObject();
                            } else {
                                data = JSONObject.parseObject(attribute);
                            }
                            if (null == data) {
                                data = new JSONObject();
                            }
                            data.put("token", token);
                            httpServletRequest.setAttribute("request", data.toJavaObject(apiController.paramClass()));
                        }
                    }

                }
            }
            httpServletRequest.setAttribute("tokenRequest", request);
            return true;
        } catch (FrequentlyException fe) {
            ResultModel.returnJson(httpServletResponse, ResultEnum.FREQUENTLY, fe.getMessage());
            return false;
        } catch (LoginException l) {
            ResultModel.returnJson(httpServletResponse, ResultEnum.NO_LOGIN, l.getMessage());
            return false;
        } catch (Exception e) {
            ResultModel.returnJson(httpServletResponse, ResultEnum.ERROR, e.getMessage());
            log.info("登录拦截系统异常：{}", e);
            return false;
        }
    }
}
